import type { HookCallback, HookType } from "./types";

/**
 * 钩子系统
 * 用于在请求的不同阶段注入自定义逻辑
 */
export class HookSystem {
  private hooks: Record<HookType, HookCallback[]> = {
    beforeRequest: [],
    afterResponse: [],
    onError: []
  };

  /**
   * 添加钩子
   * @param type 钩子类型
   * @param callback 钩子回调函数
   */
  public addHook(type: HookType, callback: HookCallback): void {
    this.hooks[type].push(callback);
  }

  /**
   * 移除钩子
   * @param type 钩子类型
   * @param callback 钩子回调函数
   */
  public removeHook(type: HookType, callback: HookCallback): void {
    const index = this.hooks[type].indexOf(callback);
    if (index !== -1) {
      this.hooks[type].splice(index, 1);
    }
  }

  /**
   * 触发钩子
   * @param type 钩子类型
   * @param data 数据
   * @returns 处理后的数据
   */
  public async triggerHook(type: HookType, data: any): Promise<any> {
    let result = data;

    for (const hook of this.hooks[type]) {
      result = await hook(result);
    }

    return result;
  }

  /**
   * 清除指定类型的所有钩子
   * @param type 钩子类型
   */
  public clearHooks(type: HookType): void {
    this.hooks[type] = [];
  }

  /**
   * 清除所有钩子
   */
  public clearAllHooks(): void {
    Object.keys(this.hooks).forEach(key => {
      this.hooks[key as HookType] = [];
    });
  }
}
